package com.tinywind.boot.common.config.security;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.tinywind.boot.common.consts.SystemConst;
import com.tinywind.boot.module.system.service.SysRolePermissionService;
import com.tinywind.boot.module.system.service.SysUserRoleService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author liuxingyu01
 * @date 2022-03-23 22:28
 * @description
 **/
@Component
public class SaTokenStpInterfaceImpl implements StpInterface {


    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRolePermissionService sysRolePermissionService;

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 1. 从session中获取
        List<String> list = (List<String>) StpUtil.getTokenSession().get(SystemConst.SYSTEM_USER_ROLE);

        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        // 2. 数据库查询用户拥有的角色码
        Set<String> roleSet = sysUserRoleService.listUserRoleByUserId(String.valueOf(loginId));
        list = new ArrayList<>(roleSet);
        // 3. 存入session中
        if (CollectionUtils.isNotEmpty(list)) {
            StpUtil.getTokenSession().set(SystemConst.SYSTEM_USER_ROLE, list);
        }
        // 4. 返回角色码集合
        return list;
    }

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 1. 从session中获取
        List<String> list = (List<String>) StpUtil.getTokenSession().get(SystemConst.SYSTEM_USER_PERMISSION);

        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        // 2. 数据库查询用户拥有的权限码
        Set<String> permissionSet = sysRolePermissionService.listRolePermissionByUserId(String.valueOf(loginId));
        list = new ArrayList<>(permissionSet);
        // 3. 存入session中
        if (CollectionUtils.isNotEmpty(list)) {
            StpUtil.getTokenSession().set(SystemConst.SYSTEM_USER_PERMISSION, list);
        }
        // 4. 返回权限码集合
        return list;
    }

}
